<?php
/**
* EasySEF - SEF component for Joostina CMS.
* @author:      Лаборатория сайтов, http://sitelab.net.ru
* @version:     1.1
* @release:     2010.01.07
* @package:     com_sef
* @copyright:   (C) 2010 http://sitelab.net.ru,  see /administrator/components/com_sef/copyright.php
* @license:     http://www.gnu.org/copyleft/gpl.html GNU/GPL
*
* Cоздан на базе sh404SEF  (C) 2007 by Yannick Gaultier
**/

defined( '_VALID_MOS' ) or die('');

// V 1.2.4.t improved upgrading
function shDeletetable( $tableName) {
  $database = &database::getInstance();
    $sql = 'DROP TABLE #__'.$tableName;
  $database->setQuery( $sql);
  $database->query();
}

function shDeleteAllSEFUrl( $kind) {
  $database = &database::getInstance();
  global $mosConfig_absolute_path;

  $sql = 'DELETE FROM #__easysef_redirection WHERE ';
  If ($kind == 'Custom')
  $where = '`dateadd` > \'0000-00-00\' and `newurl` != \'\';';
  else
  $where = '`dateadd` = \'0000-00-00\';';
  $database->setQuery($sql.$where);
  $database->query();
}

function shWriteModuleConfig( $modName, $shConfig, $pub, $sefConfig) {
  global $mosConfig_absolute_path, $mosConfig_live_site;
  if (empty($shConfig)) return;
  $moduleFile = $mosConfig_absolute_path.'/media/easysef_upgrade_'.$modName.'_'
  .str_replace('/','_',str_replace('http://', '', $mosConfig_live_site)).'.php';
  @unlink($moduleFile);  // remove previous if any
  $data = '<?php // Module params save file for easysef
//'.$sefConfig->version.'    
if (!defined(\'_VALID_MOS\')) die(\'\');
$shConfig = ';
  $data .= var_export( $shConfig, true). ';';
  // save pages the module is published on
  $data .= "\n".'$shPub = '.var_export( $pub, true).';';
  $data .= "\n".'?'.'>';
  $moduleFileHandle=fopen( $moduleFile,'wb');
  if ($moduleFileHandle) {
    fwrite( $moduleFileHandle, $data);
    fclose( $moduleFileHandle);
  }
}


function shSaveModuleParam( $modName, $shConfig) {
  $database = &database::getInstance();
  global $mosConfig_absolute_path, $mosConfig_live_site;

  $sql = 'SELECT id, title, ordering, position, published, access, showtitle, params FROM `#__modules` WHERE `module`= \''.$modName.'\';';
  $database->setQuery($sql);
  $result = $database->loadAssocList();
  $modId = $result[0]['id'];
  unset($result[0]['id']); // we don't want to save DB id
  if ($shConfig->shKeepModulesSettingsOnUpgrade) {
    // find pages the module is published on
    $sql = "SELECT menuid FROM #__modules_menu WHERE moduleid = " . (int) $modId;
    $database->setQuery( $sql );
    $rows = $database->loadResultArray();
    $pub = array();
    foreach($rows as $menuid) {
      $pub[] = $menuid;
    }
    // write everything on disk
    shWriteModuleConfig($modName, $result[0], $pub, $shConfig);
  } else {
    $moduleFile = $mosConfig_absolute_path.'/media/easysef_upgrade_'.$modName.'_'
    .str_replace('/','_',str_replace('http://', '', $mosConfig_live_site)).'.php';
    @unlink($moduleFile);
  }
  // now remove also module publication pages
  $sql='DELETE FROM #__modules_menu WHERE moduleid = ' . (int) $modId;
  $database->setQuery( $sql );
  $database->query( $sql );
}

function com_uninstall() {
  $database = &database::getInstance();
  global $mosConfig_absolute_path, $mosConfig_live_site;
  // V 1.2.4.t before uninstalling modules, save their settings, if told to do so
  $sef_config_class = $GLOBALS['mosConfig_absolute_path']."/administrator/components/com_sef/easysef.class.php";
  // Make sure class was loaded.
  if (!class_exists('SEFConfig')) {   // V 1.2.4.T was wrong variable name $SEFConfig_class instead of $sef_config_class
    if (is_readable($sef_config_class)) require_once($sef_config_class);
    else die(_COM_SEF_NOREAD."( $sef_config_class )<br />"._COM_SEF_CHK_PERMS);
  }
  $sefConfig = new SEFConfig();
  if (!$sefConfig->shKeepStandardURLOnUpgrade && !$sefConfig->shKeepCustomURLOnUpgrade) {
    shDeleteTable('easysef_redirection');
    shDeleteTable('easysef_aliases');
  }
  elseif (!$sefConfig->shKeepStandardURLOnUpgrade)
  shDeleteAllSEFUrl('Standard');
  elseif (!$sefConfig->shKeepCustomURLOnUpgrade) {
    shDeleteAllSEFUrl('Custom');
    shDeleteTable('easysef_aliases');
  }
  if (!$sefConfig->shKeepMetaDataOnUpgrade)
  shDeleteTable('easysef_meta');
   
  shSaveModuleParam( 'mod_easysef_custom_tags', $sefConfig);

  // uninstall modules
  $database->setQuery( "DELETE FROM `#__modules` WHERE `module`= 'mod_easysef_custom_tags';");
  $database->query();
  @unlink( "$mosConfig_absolute_path/modules/mod_easysef_custom_tags.css" );
  @unlink( "$mosConfig_absolute_path/modules/mod_easysef_custom_tags.php" );
  @unlink( "$mosConfig_absolute_path/modules/mod_easysef_custom_tags.xml" );

  // preserve configuration or not ?
  if (!$sefConfig->shKeepConfigOnUpgrade) {
    @unlink( $mosConfig_absolute_path.'/media/easysef_upgrade_conf_'
    .str_replace('/','_',str_replace('http://', '', $mosConfig_live_site)).'.php');
    @unlink( $mosConfig_absolute_path.'/media/easysef_upgrade_conf_'
    .str_replace('/','_',str_replace('http://', '', $mosConfig_live_site)).'.default.php');
    @unlink($mosConfig_absolute_path.'/media/easysef_upgrade_mod_easysef_custom_tags_'
    .str_replace('/','_',str_replace('http://', '', $mosConfig_live_site)).'.php');
    if ($handle = opendir(EASYSEF_ADMIN_ABS_PATH.'logs/')) {
      while (false !== ($file = readdir($handle))) {
        if ($file != '.' && $file != '..')
        @unlink($mosConfig_absolute_path.'/media/easysef_upgrade_conf_logs/'.$file);
      }
      closedir($handle);
    }
    if ($handle = opendir(EASYSEF_ADMIN_ABS_PATH.'security/')) {
      while (false !== ($file = readdir($handle))) {
        if ($file != '.' && $file != '..')
        @unlink($mosConfig_absolute_path.'/media/easysef_upgrade_conf_security/'.$file);
      }
      closedir($handle);
    }
  }
  // must move log files out of the way, otherwise administrator/com_sef/logs will not be deleted
  // and next installation of com_sef will fail
  else { // if we keep config
    // make dest dir
    @mkdir($mosConfig_absolute_path.'/media/easysef_upgrade_conf_logs');
    @mkdir($mosConfig_absolute_path.'/media/easysef_upgrade_conf_security');
    if ($handle = opendir(EASYSEF_ADMIN_ABS_PATH.'logs/')) {
    		while (false !== ($file = readdir($handle))) {
    		  if ($file != '.' && $file != '..' && $file != 'index.html')
    		  @rename(EASYSEF_ADMIN_ABS_PATH.'logs/'.$file,
    		  $mosConfig_absolute_path.'/media/easysef_upgrade_conf_logs/'.$file);
    		}
    		closedir($handle);
    }
    if ($handle = opendir(EASYSEF_ADMIN_ABS_PATH.'security/')) {
    		while (false !== ($file = readdir($handle))) {
    		  if ($file != '.' && $file != '..' && $file != 'index.html')
    		  @rename(EASYSEF_ADMIN_ABS_PATH.'security/'.$file,
    		  $mosConfig_absolute_path.'/media/easysef_upgrade_conf_security/'.$file);
    		}
    		closedir($handle);
    }
  }
  echo '<h3>EasySEF и системный модуль easysef_custom_tags успешно удалены. </h3>';
  echo '<br />';
  if ($sefConfig->shKeepStandardURLOnUpgrade)
  echo '- автоматически созданные SEF url не удалены и сохраняются в базе данных (таблица #__easysef_redirection)<br />';
  else
  echo '- автоматически созданные SEF url были удалены<br />';
  echo '<br />';
  if ($sefConfig->shKeepCustomURLOnUpgrade)
  echo '- пользовательские SEF url и алиасы не удалены и сохраняются в базе данных (таблицы #__easysef_redirection и easysef_aliases)<br />';
  else
  echo '- пользовательские SEF url и алиасы были удалены<br />';
  echo '<br />';
  if ($sefConfig->shKeepMetaDataOnUpgrade)
  echo '- Пользовательские Title and META тэги не удалены и сохраняются в базе данных (таблица #__easysef_meta)<br />';
  else
  echo '- Пользовательские Title and META тэги были удалены<br />';
  echo '<br />';
  if ($sefConfig->shKeepModulesSettingsOnUpgrade)
  echo '- параметры модуля mod_easysef_custom_tags не удалены<br />';
  else
  echo '- параметры модуля mod_easysef_custom_tags были удалены<br />';
  echo '<br />';
   
}
